﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Sprout.Core.Utils
{
    public class StrHelper
    {
        /// <summary>
        /// 根据正则提取开始和结束字符之间的关联词
        /// </summary>
        /// <param name="value">内容</param>
        /// <param name="begin">开始符</param>
        /// <param name="end">结束符</param>
        /// <param name="contain">是否包含开始符和结束符</param>
        /// <returns></returns>
        public static List<string> ExtractKeywords(string value, string begin, string end, bool contain = true)
        {
            string pattern = string.Format("[{0}].*?[{1}]", begin, end);
            MatchCollection mc = Regex.Matches(value, pattern);
            List<string> list = new List<string>();
            foreach (Match match in mc)
            {
                var v = match.ToString();
                if (!contain)
                {
                    v = v.TrimStart(begin.ToCharArray());
                    v = v.TrimEnd(end.ToCharArray());
                }
                list.Add(v);
            }
            return list;
        }
        /// <summary>
        /// 根据属性名替换文本内容
        /// </summary>
        /// <param name="content">文本</param>
        /// <param name="keyValues">参数</param>
        /// <param name="begin">属性名前增加的拼接字符</param>
        /// <param name="end">属性名后增加的拼接字符</param>
        /// <returns>替换后的文本</returns>
        public static string Replace(string content, Dictionary<string, string> keyValues, string begin = "", string end = "")
        {
            if (keyValues == null || keyValues.Keys.Count == 0)
            {
                return content;
            }
            foreach (string key in keyValues.Keys)
            {
                string oldValue = $"{begin}{key}{end}";
                if (keyValues[key] != null)
                {
                    content = content.Replace(oldValue, keyValues[key]?.ToString());
                }
            }
            return content;
        }
    }
}
